package main

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	surreal "github.com/surrealdb/surrealdb.go"
)

type Movie struct {
	ID    string `json:"id,omitempty"`
	Title string `json:"title"`
	Year  int    `json:"year"`
	Genre string `json:"genre"`
}

var db *surreal.DB

func main() {
	// 连接 SurrealDB
	var err error
	db, err = surreal.New("ws://localhost:8000/rpc")
	if err != nil {
		panic(err)
	}
	// 登录（root 用户，实际环境请安全存储密码）
	if _, err = db.Signin(map[string]interface{}{
		"user": "root",
		"pass": "root",
	}); err != nil {
		panic(err)
	}
	// 选择 namespace 和 database
	if _, err = db.Use("test", "test"); err != nil {
		panic(err)
	}

	r := gin.Default()

	r.POST("/movies", func(c *gin.Context) {
		var m Movie
		if err := c.ShouldBindJSON(&m); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		// 使用Create方法
		_, err := db.Create("movie", m)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "Movie created"})
	})

	// 获取所有movie 的接口
	r.GET("/movies", func(c *gin.Context) {
		// 使用Select方法
		result, err := db.Select("movie")
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		// 处理SurrealDB返回的数据格式
		if movies, ok := result.([]interface{}); ok {
			for _, movie := range movies {
				if m, ok := movie.(map[string]interface{}); ok {
					// 清理ID格式
					if id, ok := m["id"].(string); ok {
						m["id"] = id[len("movie:"):]
					}
				}
			}
			c.JSON(http.StatusOK, movies)
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "invalid SurrealDB response format"})
		}
	})

	// 拼接 SELECT * FROM movie where title  = '张22';

	// 根据 title 过滤电影的 方法
	r.GET("/movies/title/:title", func(c *gin.Context) {
		title := c.Param("title")
		// 使用Select方法
		result, err := db.Select("movie")
		if err == nil {
			if movies, ok := result.([]interface{}); ok {
				filtered := make([]interface{}, 0)
				for _, movie := range movies {
					if m, ok := movie.(map[string]interface{}); ok {
						if m["title"] == title {
							filtered = append(filtered, m)
						}
					}
				}
				result = filtered
			}
		}
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 处理SurrealDB返回的数据格式
		if movies, ok := result.([]interface{}); ok {
			for _, movie := range movies {
				if m, ok := movie.(map[string]interface{}); ok {
					// 清理ID格式
					if id, ok := m["id"].(string); ok {
						m["id"] = id[len("movie:"):]
					}

					// 清理年份格式
					if year, ok := m["year"].(float64); ok {
						m["year"] = int(year)
					}
					// 清理年份格式
				}
			}
			c.JSON(http.StatusOK, movies)
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "invalid SurrealDB response format"})
		}
	})

	r.GET("/movies/:id", func(c *gin.Context) {
		id := c.Param("id")
		// 使用 query 方法
		// 	userData, err = db.Query("select * from users where id = $id", map[string]interface{}{
		//		"id": "users:jim",
		//	})
		result, err := db.Query("SELECT * FROM movie where id  = $id", map[string]interface{}{
			"id": "movie:" + id,
		})
		fmt.Println(result)

		if err != nil {
			fmt.Println(err)
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 处理SurrealDB返回的数据格式
		// [map[result:[map[genre:action id:movie:z37z9dnwlp95vu67xtm1 title:张22 year:2025]] 转成json
		// ] 转成json
		if movies, ok := result.([]interface{}); ok {
			for _, movie := range movies {
				if m, ok := movie.(map[string]interface{}); ok {
					// 清理ID格式
					if id, ok := m["id"].(string); ok {
						m["id"] = id[len("movie:"):]
					}

					// 清理年份格式
					if year, ok := m["year"].(float64); ok {
						m["year"] = int(year)
					}
					// 清理年份格式
				}
			}
			c.JSON(http.StatusOK, movies)
			return
		}

		c.JSON(http.StatusInternalServerError, gin.H{"error": "invalid SurrealDB response format"})
		return
	})

	r.PUT("/movies/:id", func(c *gin.Context) {
		id := c.Param("id")
		var m Movie
		if err := c.ShouldBindJSON(&m); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		// 使用Update方法
		_, err := db.Update("movie:"+id, m)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "Movie updated"})
	})

	r.DELETE("/movies/:id", func(c *gin.Context) {
		id := c.Param("id")
		// 使用Delete方法
		_, err := db.Delete("movie:" + id)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "Movie deleted"})
	})

	r.Run(":8080")
}
